package com.linewow.xhyy.nihaonew.activity;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ImageView;

import com.linewow.xhyy.hrxb.DemoHelper;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseActivity;
import com.linewow.xhyy.nihaonew.db.NiHaoHelper;
import com.linewow.xhyy.nihaonew.entity.NiHaoGeneral;
import com.linewow.xhyy.nihaonew.entity.user.HuanXinUserInfo;
import com.linewow.xhyy.nihaonew.net.NihaoNetWork;
import com.linewow.xhyy.nihaonew.net.api.NiHaoOkgo;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by LXR on 2016/9/30.
 */
public class WelcomeActivity extends BaseActivity {
    @Bind(R.id.welcome_image)
    ImageView welcomeImage;

    private NiHaoHelper niHaoHelper;
    private String TAG="WelcomeActivity";



    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_welcome);
        ButterKnife.bind(this);
        niHaoHelper=NiHaoHelper.getInstance();
        Log.e(TAG,"okgo更改了==");
        NiHaoOkgo.shieldInfo("shieldoff","1318")//这是刘50
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NiHaoGeneral<String>>() {
                    @Override
                    public void call(NiHaoGeneral<String> stringNiHaoGeneral) {
                        if (stringNiHaoGeneral.info != null) {
                            DemoHelper.getInstance().logoutUpdate();
                            startAnim();
                            Log.e(TAG, "token失效了");
                        } else {
                            requestInfo();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                       startAnim();
                    }
                });
    }

    private void requestInfo() {
        Log.e(TAG,"token值"+NiHaoApp.token);
        if(NiHaoApp.token.equals("")){
            startAnim();
        }else{
            String codeToken=null;
            try {
                codeToken= URLEncoder.encode(NiHaoApp.token,"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            NihaoNetWork.getNiHaoService()
                    .huanxinUser(codeToken)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<HuanXinUserInfo>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }
                        @Override
                        public void onNext(HuanXinUserInfo huanXinUserInfo) {
                            if(huanXinUserInfo.status){
                                NiHaoApp.nick=huanXinUserInfo.nickname;
                                Log.e(TAG,"昵称-->"+NiHaoApp.nick);

                                JPushInterface.setAlias(NiHaoApp.getInstance().getApplicationContext(), huanXinUserInfo.username, new TagAliasCallback() {
                                    @Override
                                    public void gotResult(int i, String s, Set<String> set) {
                                        Log.e(TAG,"jpush设置完成了"+s+"---"+i);
                                    }
                                });

                                hrxbLogin(huanXinUserInfo);

                            }else{
                                //token失效的情况下  这种情况不会发生 php说这里得token不经过验证 永远不会出现token过期
                                DemoHelper.getInstance().logoutUpdate();
                                startAnim();
                            }
                        }
                    });
        }
    }

    private void hrxbLogin(HuanXinUserInfo huanXinUserInfo) {
        startAnim();
//        DemoDBManager.getInstance().closeDB();
//        DemoHelper.getInstance().setCurrentUserName(huanXinUserInfo.username);
//        EMClient.getInstance().login(huanXinUserInfo.username, huanXinUserInfo.password, new EMCallBack() {
//            @Override
//            public void onSuccess() {
//                EMClient.getInstance().groupManager().loadAllGroups();
//                EMClient.getInstance().chatManager().loadAllConversations();
//
//                // update current user's display name for APNs
//                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
//
//                final EaseUser user=DemoHelper.getInstance().getUserProfileManager().getCurrentUserInfo();
//                Observable.just(user.toString())
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Action1<String>() {
//                            @Override
//                            public void call(String s) {
//                                startAnim();
//                            }
//                        });
//            }
//
//            @Override
//            public void onError(int i, String s) {
//                Log.e(TAG, "错误代码：" + i + "登录失败了:" + s);
//            }
//
//            @Override
//            public void onProgress(int i, String s) {
//                Log.e(TAG,"正在登录中"+s);
//            }
//        });
    }

    private void startFrameActivity() {
        startActivity(new Intent(WelcomeActivity.this, FrameActivity.class));
        WelcomeActivity.this.finish();
    }


    private void startAnim() {
        ObjectAnimator animatorX = ObjectAnimator.ofFloat(welcomeImage, "scaleX", 1f, 1f);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(welcomeImage, "scaleY", 1f, 1f);


        AnimatorSet set = new AnimatorSet();
        set.setDuration(2000).play(animatorX).with(animatorY);
        set.start();

        set.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                int time=niHaoHelper.getStoreInfo();
                Log.e(TAG,"进入的次数"+time);
                if(time==1){
                    startFrameActivity();
                }else{
                    startStartActivity();
                }
            }
        });
    }

    private void startStartActivity() {
        startActivity(new Intent(WelcomeActivity.this, StartActivity.class));
        WelcomeActivity.this.finish();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
